package com.demo.accept;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.omg.CORBA.Environment;

import com.demo.bean.Enviroment;
import com.demo.store.StoreImpl;
import com.demo.util.CollectionOracle;

/**
 * 使用线程处理客户端每次发过来的数据
 * 使用多线程处理
 * @author ASUS
 *
 */
public class AcceptImpl implements IAccept {
	
	private static final Logger logger = Logger.getLogger(AcceptImpl.class);

	@Override
	public void accep() {
		int port = 9999;
		
		try {
			ServerSocket server = new ServerSocket(port);
//			System.out.println("服务器端已建立，等待客户连接...");
			logger.info("服务端已建立，等待客户连接...");
			/**
			 * accept完成，三次握手建立成功
			 */
//			Socket socket = server.accept();
//			System.out.println("客户端已连接："+socket);
			
//			ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//			
//			Object object = ois.readObject();
//			
//			Collection<? extends Enviroment> list = (Collection<? extends Enviroment>) object;
//			
//			list.forEach(System.out::println);
			while(true) {
				Socket socket = server.accept();
				//对Socket进行处理
//				System.out.println("客户端已连接："+socket);
				logger.info(socket.getInetAddress() + "客户端已连接...");
				
				MyThread thread = new MyThread(socket);
				thread.start();
//				System.out.println("本次数据交给一个线程去处理");
				logger.info(socket.getInetAddress() + "客户端数据已交给一个线程处理！");
			}
			
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static class MyThread extends Thread{
		
		private Socket socket = null;
		private ObjectInputStream ois = null;
		
		//注入Socket
		public MyThread(Socket socket) {
			this.socket = socket;
		}
		
		@Override
		public void run() {
			try {
//				System.out.println(socket+"正在发送数据...");
				logger.info(socket.getInetAddress() + "正在发送数据...");
				//构建反序列化流
				ois = new ObjectInputStream(socket.getInputStream());
				
				//反序列化为集合对象
				Object object = ois.readObject();
				
				Collection<Enviroment> list = (Collection<Enviroment>) object;
				
//				list.forEach(System.out::println);
				
				StoreImpl store = new StoreImpl();
				store.store(list);
				
//				System.out.println(socket+"线程已执行完毕！");
				logger.info(socket.getInetAddress() + "发送数据完毕，线程销毁！");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				try {
					if(socket != null)
						socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}
